<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        关闭
      </a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
        保存草稿
      </a-button>
      <a-button  type="primary" key="draftText" :loading="draftLoading" @click="draftTextClick">
        起草正文
      </a-button>
      <a-button key="send" type="primary" :loading="sendLoading" @click="sendClick">
        发送
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" class="ant-form ant-form-horizontal">
        <a-card  id="staffCard" class="ant-card ant-card-bordered" style="margin: 0px auto; width: 1000px;">
          <span id="staffLeaveTitle">公文发文</span>
        <table border="1px" id="staffEvectionTable">
          <tr>
            <td><span>机关代字</span></td>
            <td>
              <a-form-item>
                <j-dict-select-tag
                  v-decorator="['organId',validatorRules.organId]"
                  :trigger-change="true"
                  dictCode="oa_officialdoc_organcode,organ_name,id"
                  placeholder="请选择机关代字"
                  @change="codeChange"/>
              </a-form-item>
            </td>
            <td>
              <span>文号：</span>
            </td>
            <td>
              <a-form-item>
                <a-input v-decorator="['code']" placeholder="请输入文号"  class="inputHeight"/>
              </a-form-item>
            </td>
          </tr>
          <tr>
            <td>
              <span>缓急：</span>
            </td>
            <td>
              <a-form-item>
                <j-dict-select-tag
                  type="list" v-decorator="['urgency']"
                  :trigger-change="true"
                  dictCode="urgency"
                  placeholder="请选择缓急" style="width:116px"/>
              </a-form-item>
            </td>
            <td>
              <span>密级：</span>
            </td>
            <td>
              <a-form-item>
                <j-dict-select-tag type="list" v-decorator="['secretLevel']"
                                   :trigger-change="true"
                                   dictCode="secret_level" placeholder="请选择密级" style="width:116px"/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td><span>部门会签：</span></td>
            <td colspan="3">
              <a-form-item>
                <a-textarea v-decorator="['jointlySigns']" class="textType" read-only/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td><span style="text-align: center">领导会签：</span></td>
            <td colspan="3">
              <a-form-item>
                <a-textarea v-decorator="['leaderJointlySigns']"  class="textType" read-only/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>拟稿人：</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <j-select-user-by-dep v-decorator="['draftUser']" :multi="false"/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td style="height: 20px">
              <span>拟稿部门：</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <j-select-depart v-decorator="['draftDept']" :customReturnField="customReturnField"/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>拟稿人意见：</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <a-textarea v-decorator="['draftUserOpinion']"  class="textType"/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>办公室核稿意见：</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <a-textarea v-decorator="['reviewUserOpinion']" class="textType" read-only/>
              </a-form-item>
            </td>

          </tr>
          <tr class="trPadding">
            <td>
              <span>办公室领导核稿意见：</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <a-textarea v-decorator="['officeLeadersOption']" class="textType" read-only/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>主办单位审核：</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <a-textarea v-decorator="['sponsorReview']"  class="textType" read-only/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>秘书审核：</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <a-textarea v-decorator="['secretaryReview']"  class="textType" read-only/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>校对意见:</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <a-textarea v-decorator="['proofreadUser']"  class="textType" read-only/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>打印份数</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <a-input-number v-decorator="['printingNumber']" class="inputHeight" />
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>标题：</span>
            </td>
            <td colspan="3" class="title">
              <a-form-item>
                <a-input v-decorator="['title',validatorRules.title]" placeholder="请输入标题"  class="inputHeight"/>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>主送：</span>
            </td>
            <td colspan="3" class="title">
              <a-form-item>
                <div style="display: flex">
                  <a-select
                    placeholder="请选择主送部门"
                    v-decorator="['mainDelivery',validatorRules.mainDelivery]"
                    mode="multiple"
                    :disabled="disabled"
                    style="margin-top: 3px;"
                  />
                  <a-button @click="selectDepart" style="margin-left: 10px;margin-top: 3px;">选择</a-button>
                </div>
              </a-form-item>
            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>抄送：</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <div style="display: flex">
                  <a-select
                    placeholder="请选择抄送部门"
                    v-decorator="['ccDelivery']"
                    mode="multiple"
                    :disabled="disabled"
                    style="margin-top: 3px;"
                  />
                  <a-button @click="selectDepartDelivery" style="margin-left: 10px;margin-top: 3px;">选择</a-button>
                </div>
              </a-form-item>

            </td>
          </tr>
          <tr class="trPadding">
            <td>
              <span>附件：</span>
            </td>
            <td colspan="3">
              <a-form-item>
                <j-upload :bizPath="filePath" v-model="fileUrl" text="附件上传"></j-upload>
              </a-form-item>

            </td>
          </tr>
        </table>
       </a-card>
        <oa-offcialdoc-select-depart-modal
          ref="departModal"
          :multi="true"
          @ok="resultOk">

        </oa-offcialdoc-select-depart-modal>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>

  import { httpAction, getAction, postAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
  import JUpload from '@/components/jeecg/JUpload'
  import oaOffcialdocSelectDepartModal from './OaOffcialdocSelectDepartModal'

  import store from '@/store'
  export default {
    name: 'OaOfficialdocIssuedModal',
    components: {
      JDate,
      JSelectDepart,
      JSelectUserByDep,
      JDictSelectTag,
      JMultiSelectTag,
      JUpload,
      oaOffcialdocSelectDepartModal
    },
    data() {
      return {
        form: this.$form.createForm(this),
        title: '操作',
        width: 1200,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        sendLoading: false,
        draftLoading: false,
        loading: false,
        validatorRules: {
          organId: {
            rules: [
              { required: true, message: '请选择机关代字!' }
            ]
          },
          title: {
            rules: [
              { required: true, message: '请填写标题!' }
            ]
          },
          mainDelivery: {
            rules: [
              { required: true, message: '请选择主送!' }
            ]
          },
        },
        url: {
          add: '/eoa/officialdoc/oaOfficialdocIssued/add',
          edit: '/eoa/officialdoc/oaOfficialdocIssued/edit',
          getCode: '/eoa/officialdoc/oaOfficialdocIssued/getCode',
          getDepartName: '/sys/sysDepart/getDepartName',
          sendText: '/eoa/officialdoc/oaOfficialdocIssued/sendText',
          getTemplateAndUser: '/eoa/officialdoc/oaOfficialdocOrgancode/getTemplateAndUser',
          getViewUrlDbPath: '/eoa/wps/oaWpsFile/getViewUrlDbPath',
          officialTemp:"/eoa/officialdoc/oaOfficialdocOrgancode/officialTemp",
          getDepartId:"/eoa/officialdoc/oaOfficialdocIssued/getDepartId",
          startProcess: "/act/process/extActProcess/startMutilProcess",
          queryPageList: "/eoa/officialdoc/oaOfficialdocDepartUser/list",
          queryDepartNameById:"/eoa/officialdoc/oaOfficialdocDepartUser/getDepartName"
        },
        fileUrl: [],
        draftText: [],
        filePath: 'enclosure',
        DrafTextPath: 'draftText',
        departName: '',
        text: false,
        draft:false,
        customReturnField:"id",
        flowCode:"officialdoc_issued",
        disabled:true,
        veryDepartIds:"",
        newVeryDepartIds:[],
        ccDepartIds:"",
        newccDepartIds:[]
      }
    },
    created() {
    },
    methods: {
      add() {
        this.edit({})
      },
      edit(record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.fileUrl = this.model.fileUrl
        this.draftText = this.model.draftText
        getAction(this.url.getDepartName, { 'orgCode': store.getters.userInfo.orgCode }).then((res) => {
          if (res.success) {
            if (this.model.id) {
              this.form.setFieldsValue({
                'draftUser': this.model.draftUser,
                'draftDept': this.model.draftDept
              })
            } else {
              getAction(this.url.getDepartId,{"sysCode":store.getters.userInfo.orgCode}).then((res) =>{
                if(res.success){
                    this.form.setFieldsValue({
                      'draftUser': store.getters.userInfo.username,
                      'draftDept': res.result
                    })
                }
              })
            }
          }
        })
        getAction(this.url.queryPageList).then((res)=>{
          if(res.success){
            var userDepart=res.result.records
            let veryDepartIds="";
            if(userDepart){
              for (let i = 0; i <userDepart.length ; i++) {
                let departId = userDepart[i].departId
                veryDepartIds+=departId+",";
              }
              if(veryDepartIds){
                this.newVeryDepartIds=veryDepartIds;
                this.newccDepartIds=veryDepartIds;
              }
            }

          }
        })
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'title', 'mainDelivery', 'ccDelivery', 'organId', 'code', 'urgency', 'secretLevel', 'issuedUser', 'jointlySigns', 'reviewUser', 'draftUserOpinion', 'reviewUserOpinion', 'proofreadUser', 'printingNumber'))
        })
        if(this.model.id){
          this.veryDepartIds=this.model.mainDelivery;
          this.ccDepartIds=this.model.ccDelivery;
          this.setDepartName(this.veryDepartIds,'mainDelivery')
          this.setDepartName(this.ccDepartIds,'ccDelivery')
        }
      },
      setDepartName(ids,fieldName){
        getAction(this.url.queryDepartNameById,{"departId":ids}).then((res)=>{
          if(res.success){
            fieldName==='mainDelivery'?this.form.setFieldsValue({ 'mainDelivery': res.result }): this.form.setFieldsValue({ 'ccDelivery': res.result })
          }
        })
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            formData.mainDelivery=this.veryDepartIds
            formData.ccDelivery=this.ccDepartIds
            formData.fileUrl = this.fileUrl
            formData.draftText = this.draftText
            formData.stauts = '0'
            console.log('表单提交数据', formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          }

        })
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'title', 'mainDelivery', 'ccDelivery', 'organId', 'code', 'urgency', 'secretLevel', 'issuedUser', 'jointlySigns', 'draftDept', 'draftUser', 'reviewUser', 'draftUserOpinion', 'reviewUserOpinion', 'proofreadUser', 'printingNumber', 'fileUrl', 'stauts', 'bpmStatus', 'createBy', 'createTime', 'updateBy', 'updateTime', 'sysOrgCode', 'draftText'))
      },
      codeChange(value) {
        getAction(this.url.getCode, { organId: value }).then((res) => {
          if (res.success) {
            this.form.setFieldsValue({ 'code': res.result })
          }
        })
      },
      draftTextClick() {
        // 起草正文，在线编辑word文档模板
        let organId = this.form.getFieldValue('organId')
        if (organId) {
          //根据机关待字获取绑定的word在线访问路径
          let code = this.form.getFieldValue('code')
          let text = "official";
          getAction(this.url.getTemplateAndUser, { 'codeId': organId,"text":text,"code":code }).then((res) => {
            if (res.success) {
              this.draftLoading = true
              const params = {
                fileId: res.result.tempId,
                userId: res.result.userId,
                text:"official"
              }
              getAction(this.url.getViewUrlDbPath, params).then((res) => {
                if (res.msg === 'ok') {
                  let r = res.data
                  sessionStorage.wpsUrl = r.wpsUrl
                  sessionStorage.token = r.token
                  let routeUrl = this.$router.resolve({
                    path: '/modules/eoa/wps/viewFile'
                  })
                  this.text = true
                  window.open(routeUrl.href, '_blank')
                } else {
                  this.$message.warning('请求错误！')
                }
                this.draftLoading = false
              })
            }
          })
        } else {
          this.$message.warning('请选择机关待字')
        }

      },
      sendClick() {
        var that = this
        this.form.validateFields((err, values) => {
          if (!err) {
            getAction(this.url.officialTemp,{"code":values.code}).then((res) =>{
              if(res.success){
                that.confirmLoading = true
                let httpurl = ''
                let method = ''
                if (!this.model.id) {
                  httpurl += this.url.add
                  method = 'post'
                } else {
                  httpurl += this.url.edit
                  method = 'put'
                }
                let formData = Object.assign(this.model, values)
                formData.mainDelivery=this.veryDepartIds
                formData.ccDelivery=this.ccDepartIds
                formData.fileUrl = this.fileUrl
                formData.draftText = this.draftText
                formData.stauts = '1'
                formData.bpmStatus = '1'
                console.log('表单提交数据', formData)
                httpAction(httpurl, formData, method).then((res) => {
                  if (res.success) {
                    if(formData.id){
                      that.startProcess(formData);
                    }else{
                      formData.id = res.result;
                      that.startProcess(formData);
                    }
                  } else {
                    that.$message.warning(res.message)
                  }
                }).finally(() => {
                  that.confirmLoading = false
                  that.close()
                })
              }else{
                this.$message.warning(res.message)
              }
            })

          }

        })

      },
      startProcess: function(record){
        var that = this;
        var param = {
          flowCode:that.flowCode,
          id:record.id,
          formUrl:"modules/eoa/officialdoc/modules/OaOfficialdocIssuedForm",
          formUrlMobile:"modules/eoa/officialdoc/modules/OaOfficialdocIssuedForm"
        }
        postAction(that.url.startProcess,param).then((res)=>{
          if(res.success){
            that.$message.success(res.message);
            that.$emit('ok')
          }else{
            that.$message.warning(res.message);
          }
        });
      },
      resultOk(data,departIds,type){
        if(data){
          var departNames = data.map(data => data['departName']).join(',')
          if("1"===type){
            this.form.setFieldsValue({"mainDelivery":[]})
            this.form.setFieldsValue({"mainDelivery":departNames})
            this.veryDepartIds=departIds;
          }else{
            this.form.setFieldsValue({"ccDelivery":[]})
            this.form.setFieldsValue({"ccDelivery":departNames})
            this.ccDepartIds=departIds;
          }
        }
      },
      selectDepart(){
        this.$refs.departModal.visible=true;
        var param=[];
        param.departIds=this.veryDepartIds;
        param.newDeparts=this.newVeryDepartIds;
        this.$refs.departModal.loadDepart(param,"1");
      },
      selectDepartDelivery(){
        this.$refs.departModal.visible=true;
        var param=[];
        param.departIds=this.ccDepartIds;
        param.newDeparts=this.newccDepartIds;
        this.$refs.departModal.loadDepart(param,"2");
      },
    }
  }
</script>


<style >
  .inputHeight {
    width: 100%;
    border: none;
    border-radius: 0;
    background:#fff;
  }

  .textType {
    resize: none;
    height: 118px !important;
    font-size: 12px;
    border: 0 solid white;
    border-radius: 0;
    margin-bottom: 0;
  }
  .textareaType{
    width: 100%;
    height: 100%;
    position: relative;
    top: 22px;
    right: 6px;
    resize:none;
  }
  .title .ant-form-explain {
    margin-top:10px !important;
  }
  #staffCard {
    border: 1px solid #fff;
    box-shadow: 0 0 1px 1px #aaa, 3px 0 5px 0 #aaa, 0 4px 7px 0 #aaa;
    border-radius: 5px;
  }
  #staffLeaveTitle {
    margin-top: 1px;
    font-weight: 700;
    text-align: center;
    display: block;
    color: #000;
    font-size: 24px;
  }
  #staffEvectionTable {
    width: 100%;
    font-size: 12px;
    text-align: center;
    background-color: #fff;
    margin-top: 10px;
  }
  #staffEvectionTable .input .ant-input, #staffEvectionTable .text {
    border: 0 solid #000!important;
    border-radius: 0;
    background-color: #fff;
    margin: 0 auto;
    width: 100%;
    font-size: 12px;
    height: 38px;
  }
  #staffEvectionTable .ant-form-item {
    margin: 0;
  }
</style>